package chaoyue.study.safe;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 因为线程池线程复用的问题
 * InheritableThreadLocal在线程池场景可能会出现值重复读取的问题
 */
public class ThreadLocalTest4 {
    private static ExecutorService executor = Executors.newFixedThreadPool(1);
    private static InheritableThreadLocal<Integer> threadLocal = new InheritableThreadLocal<>();

    public static void main(String[] args) {
        for (int i = 0; i < 5; i++) {
            final int count = i;
            threadLocal.set(i);
            // 主线程设置
            System.out.println(Thread.currentThread().getName() + "放入值，值为 : " + i);
            // 子线程获取
            executor.execute(() -> System.out.println(Thread.currentThread().getName() + "进行取值-" + count + "，值为 : " + threadLocal.get()));
            // 主线程获取
            System.out.println(Thread.currentThread().getName() + "进行取值，值为 : " + threadLocal.get());
            // 清除ThreadLocal中的内容
            threadLocal.remove();
        }
        executor.close();
    }
}
